package com.huluobo.a2301mdmdemo.pages

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.huluobo.a2301mdmdemo.R
import com.huluobo.a2301mdmdemo.demo.BezierLineView
import com.huluobo.a2301mdmdemo.demo.LikeView
import com.huluobo.a2301mdmdemo.pay.PayPage
import com.huluobo.lib_base.RoutePath
import com.hyphenate.EMMessageListener
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMConversation
import com.hyphenate.chat.EMGroup
import com.hyphenate.chat.EMMessage.ChatType
import com.hyphenate.chat.EMTextMessageBody
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date

/**
 *  Created by LC on 2025/6/23.
 */

@Composable
fun MessagePage(navHostController: NavHostController) {
    val allConversations = remember {
        SnapshotStateList<EMConversation>()
    }

    var isLoad by remember {
        mutableStateOf(false)
    }
    //消息监听器
    val messageListener = EMMessageListener {
        //当接收到消息的时候,直接添加数据到数据中
        isLoad = true
    }
    //类似于activity的生命周期
    DisposableEffect(Unit) {
        //带生命周期的协程作用域
        EMClient.getInstance().chatManager().addMessageListener(messageListener)

        //当页面销毁时
        onDispose {
            //销毁时移除掉消息监听器
            EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        }
    }

    LaunchedEffect(key1 = isLoad, block = {
        launch {
            allConversations.clear()
            //将读取到的所有会话列表中的值添加到数据源中
            allConversations.addAll(EMClient.getInstance().chatManager().allConversations.values)
            allConversations.sortByDescending { it.lastMessage.msgTime }
            isLoad = false
        }
    })

    Column(
        Modifier
            .fillMaxWidth()
            .padding(20.dp)
    ) {
        Text(text = "消息", fontSize = 26.sp, fontWeight = FontWeight.Bold)
        Spacer(modifier = Modifier.height(10.dp))
        LazyColumn(content = {
            items(allConversations) {
                ConversationItem(emConversation = it, navHostController = navHostController)
            }
        }, verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth())
    }
}

@Composable
fun ConversationItem(emConversation: EMConversation, navHostController: NavHostController) {
    val isGroup by remember {
        mutableStateOf(emConversation.lastMessage.chatType == ChatType.GroupChat)
    }

    var groupName by remember {
        mutableStateOf("")
    }

    if (emConversation.isGroup) {
        EMClient.getInstance().groupManager()
            .asyncGetGroupFromServer(emConversation.conversationId(), object : EMValueCallBack<EMGroup> {
                override fun onSuccess(value: EMGroup?) {
                    if (value != null) {
                        groupName = value.groupName
                    }
                }

                override fun onError(error: Int, errorMsg: String?) {
                }
            })
    }

    Row(verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(10.dp),
        modifier = Modifier
            .fillMaxWidth()
            .padding(10.dp)
            .clickable {
                //标记当前会话中所有消息为已读
                emConversation.markAllMessagesAsRead()
                //点击跳转到对应的聊天页面
                if (emConversation.type == EMConversation.EMConversationType.Chat) {
                    val chatBean = ChatBean(emConversation.conversationId(), ChatType.Chat, "")
                    val json = Gson().toJson(chatBean)
                    navHostController.navigate(RoutePath.CHAT + "/$json")
                } else {
                    val chatBean = ChatBean(emConversation.conversationId(), ChatType.GroupChat, groupName)
                    val json = Gson().toJson(chatBean)
                    navHostController.navigate(RoutePath.CHAT + "/$json")
                }

            }) {
        AsyncImage(
            model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
            contentDescription = "",
            modifier = Modifier
                .size(50.dp)
                .clip(RoundedCornerShape(5.dp)),
            contentScale = ContentScale.Crop
        )
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
            Column(Modifier.height(50.dp), verticalArrangement = Arrangement.SpaceAround) {
                if (isGroup) {
                    Text(text = groupName)
                } else {
                    Text(text = emConversation.conversationId())
                }
                Text(text = (emConversation.lastMessage.body as EMTextMessageBody).message, color = Color.LightGray)
            }

            Column(modifier = Modifier.height(50.dp), verticalArrangement = Arrangement.SpaceAround, Alignment.End) {
                val today = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                //获取最后一条消息中的年月日
                val date = TimeUtils.date2String(Date(emConversation.lastMessage.msgTime)).substring(0, 10)
                //获取最后一条消息的时分秒
                val time = TimeUtils.date2String(Date(emConversation.lastMessage.msgTime)).substring(10, 16)
                if (date == today) {
                    Text(text = time)
                } else {
                    Text(text = date.substring(5, 10))
                }

                if (emConversation.unreadMsgCount > 0) {
                    Text(
                        text = emConversation.unreadMsgCount.toString(),
                        color = Color.White,
                        modifier = Modifier
                            .background(
                                Color.Red,
                                CircleShape
                            )
                            .size(16.dp), fontSize = 10.sp, textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}